<template>
  <div
    class="InputCommBox"
    :class="{
      dark: themeRef.state.themeState == 'drak',
      light: themeRef.state.themeState == 'light',
    }"
  >
    <div
      class="title"
      :class="{
        dark: themeRef.state.themeState == 'drak',
        light: themeRef.state.themeState == 'light',
      }"
    >
      <textarea
        type="text"
        :class="{
          dark_input: themeRef.state.themeState == 'drak',
          light_input: themeRef.state.themeState == 'light',
        }"
        :placeholder="option.placeholder"
        v-model="textareaRef"
      />

      <div class="operation">
        <div class="operationLeft">
          <span
            v-show="option.emoji"
            class="iconfont icon-emoji"
            title="点击选择表情"
            @click="emojiShowOrHide"
          ></span>
          <span
            class="iconfont icon-shipinbofang"
            title="点击选择视频"
            v-show="option.video"
          ></span>
          <input
            type="file"
            multiple
            title="视频最大:500MB,视频格式mp4"
            class="fileVideo"
            accept="video/*"
            @change="uploadVideo"
            @click="uploadVideoClick"
          />
          <span
            class="iconfont icon-tupian"
            title="点击选择图片"
            v-show="option.image"
          ></span>
          <input
            type="file"
            @change="selectImg"
            @click="clickSelectImg"
            multiple
            accept="image/*"
            title="一次上传最多9张。图片类型：JPG,PNG,JPEG"
            class="fileImage"
          />
          <el-checkbox
            v-model="isRef"
            label="允许转发"
            size="small"
            class="ml5"
            v-show="option.permissions"
          />
          <el-checkbox
            v-model="isComm"
            label="允许评论"
            size="small"
            class="ml5"
            v-show="option.permissions"
          />
        </div>
        <div>
          <div class="button" @click="upload(blogID)">
            {{ option.buttonText }}
          </div>
          <div
            class="button clse"
            v-show="blogType != '0'"
            @click="cancelUpload"
          >
            取消
          </div>
        </div>

        <!-- emoji表情 -->
        <div
          @mouseleave="emojiShowOrHide"
          v-show="emojiShowOrHideRef"
          class="emojiBox"
          :class="{
            dark_input: themeRef.state.themeState == 'drak',
            light_input: themeRef.state.themeState == 'light',
          }"
        >
          <span v-for="item in emojiDataRef" :key="item.id" @click="copyEmoji">
            {{ item.text }}
          </span>
        </div>
      </div>
    </div>
    <div class="blogImage" v-show="blogImageArr.length != 0">
      <div
        v-for="(item, index) in blogImageArr"
        :key="item.id"
        v-loading="loadingRef"
      >
        <img
          :src="item.thumbnail"
          @load="imageOk"
          @error="imageRefUrl($event, index)"
        />
      </div>
    </div>
    <!-- 视频上传浏览界面 -->
    <div class="blogVideo" v-show="blogType == '2'">
      <img
        :src="videoUploadRef.captureCoverImage"
        @error="videoRefUrl"
        v-loading="videoLoadingRef"
        @load="videoImageLoad"
        alt="加载中..."
      />
      <div
        class="jdt"
        :class="{ done: progressRef == 100 }"
        :style="{ width: progressRef + '%' }"
      >
        {{ progressRef }}%
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Vue, Options } from "vue-class-component";
import { useStore } from "vuex";
import { emoji as emojiData } from "@/data/emoji";
import ins from "@/utils/Axios";
import { ElMessage } from "element-plus";
import axios from "axios";
@Options({
  components: {},
  props: { option: Object, blogID: String },
  watch: {},
  computed: {},
  mounted() {
    this.typeRef = this.option.video;
    this.topic = this.option.type;
    this.permissions = this.option.permissions;
  },
})
export default class BlogItem extends Vue {
  themeRef: any = useStore();

  textareaRef: String = "";

  textareaLengthRef: number = 0;

  permissions: boolean = false;

  // 文章的所属话题
  topic: string = "";

  // 发表博文是否可以转发
  isRef: boolean = true;

  // 博文是否可以评论
  isComm: boolean = true;

  // emoji表情数据
  emojiDataRef: Array<Object> = emojiData;

  typeRef: boolean = true;

  // 博客类型 0 仅文字 1 图文 2视频文字
  blogType: "0" | "1" | "2" = "0";

  // 图文博客中的图
  blogImageArr: any = [];

  // 加载是否成功？
  loadingRef: boolean = true;

  // 视频信息
  videoUploadRef: any = {};

  // 视频上传进度
  progressRef: number = 0;

  // 视频封面是否加载成功？
  videoLoadingRef: boolean = true;

  // 发表评论
  upload(blogID: string): void {
    if (!localStorage.getItem("userID")) {
      ElMessage.error("您还未登录！");
      return;
    }
    if (this.textareaRef) {
      let obj: any = this.typeRef
        ? {
            type: 0,
            refwordUrl: "NULL",
            blogContent: this.textareaRef,
          }
        : {
            messageContent: this.textareaRef,
            userId: localStorage.getItem("userID"),
            blogId: blogID,
          };

      //图文处理
      if (this.blogType == "1" && this.typeRef) {
        obj.type = 1;
        obj.blogImg = JSON.stringify(this.blogImageArr);
      }

      if (this.blogType == "2" && this.typeRef) {
        obj.type = 2;
        obj.blogVideo = JSON.stringify(this.videoUploadRef);
      }

      if (this.topic == "topic") {
        console.log(this.$route.params.id);
        obj.blogTitle = this.$route.params.id;
      }
      if (this.permissions) {
        if (this.isRef && this.isComm) {
          obj.permissions = 1;
        } else if (!this.isRef && !this.isComm) {
          obj.permissions = -1;
        } else if (!this.isRef) {
          obj.permissions = 2;
        } else if (!this.isComm) {
          obj.permissions = 3;
        }
      }
      console.log(obj);
      ins
        .post(
          this.typeRef ? "/blog/createBlog" : "/message/addBlogMessage",
          obj
        )
        .then((res: any) => {
          let { data } = res;
          this.textareaRef = "";
          this.$emit("reflush", 0);
          if (data.flag) {
            ElMessage.success("发布成功!");
          } else {
            ElMessage.error("【发布失败】" + data.msg);
          }
        })
        .catch((err: any) => {
          ElMessage.error("网络请求超时！请检查网络后重试！");
        });
    } else {
      ElMessage.error("写点什么东西吧！");
    }
  }

  // 将EMOJI放入txt
  copyEmoji(e: any): void {
    this.textareaRef += e.target.innerText;
    this.textareaLengthRef++;
  }

  emojiShowOrHideRef: boolean = false;

  // emoji表情显示与隐藏
  emojiShowOrHide(e: any): void {
    this.emojiShowOrHideRef = !this.emojiShowOrHideRef;
  }

  // 上传图片
  selectImg(e: any): void {
    if (!localStorage.getItem("userID")) {
      ElMessage.error("您还未登录！");
      return;
    }
    const file = e.target;
    let fd = new FormData();
    let fs = file.files;
    if (this.blogType != "0") {
      ElMessage.error("图文/视频文只可选其一!");
    }
    for (let i = 0; i < fs.length; i++) {
      if (
        fs[i].type == "image/png" ||
        fs[i].type == "image/jpg" ||
        fs[i].type == "image/jpeg"
      ) {
        fd.append("BlogImg", fs[i]);
      } else {
        ElMessage.error("图片格式错误!");
        return;
      }
    }

    if (fd.getAll("BlogImg").length > 9) {
      ElMessage.error("每个博文最大可上传9个图片!");
      return;
    }
    this.blogType = "1";
    this.loadingRef = true;
    axios
      .post("https://www.lv666.top:8882/file/BlogImg", fd, {
        headers: {
          "Content-Type": "multipart/form-data",
          authorization: localStorage.getItem("token") || "",
        },
        onUploadProgress: (progressEvent: any) => {
          //计算上传了多少
          let complete =
            ((progressEvent.loaded / progressEvent.total) * 100) | 0;
          console.log(complete);
        },
      })
      .then((res: any) => {
        this.blogImageArr = res.data.data;
      })
      .catch((err: any) => {
        console.log(err);
      });
  }

  // 查看是否满足上传图片的条件
  clickSelectImg(e: any): void {
    let arr: Array<string> = ["2"];
    if (arr.indexOf(this.blogType) != -1) {
      e.preventDefault();
      ElMessage.error("图文/视频文只可选其一!");
      return;
    }
  }

  // 刷新图片
  imageRefUrl(e: any, index: any): void {
    e.target.src = this.blogImageArr[index].thumbnail;
  }

  // 加载图片
  imageOk() {
    this.loadingRef = false;
  }

  // 上传视频
  uploadVideo(e: any) {
    if (!localStorage.getItem("userID")) {
      ElMessage.error("您还未登录！");
      return;
    }
    const file: any = e.target;
    let fd: any = new FormData();
    let fs: any = file.files;
    if (this.blogType != "0") {
      ElMessage.error("图文/视频文只可选其一!");
      return;
    }
    if (fs[0].name.indexOf(" ") != -1) {
      ElMessage.error("【文件名称不合法】出现了违规字符或者空格!");
      return;
    }
    this.blogType = "2";

    fd.append("BlogVideo", fs[0]);
    axios
      .post("https://www.lv666.top:8882/file/BlogVideo", fd, {
        headers: {
          "Content-Type": "multipart/form-data",
          authorization: localStorage.getItem("token") || "",
        },
        onUploadProgress: (progressEvent: any) => {
          //计算上传了多少
          let complete =
            ((progressEvent.loaded / progressEvent.total) * 100) | 0;
          this.progressRef = complete;
        },
      })
      .then((res: any) => {
        this.videoUploadRef = res.data.data;
      });
  }

  // 更新视频封面
  videoRefUrl(e: any) {
    e.target.src = this.videoUploadRef.captureCoverImage;
  }

  // 查看是否满足上传视频的条件
  uploadVideoClick(e: any): void {
    let arr: Array<string> = ["1"];
    if (arr.indexOf(this.blogType) != -1) {
      e.preventDefault();
      ElMessage.error("图文/视频文只可选其一!");
      return;
    }
  }

  videoImageLoad() {
    this.videoLoadingRef = false;
  }

  // 取消上传
  cancelUpload() {
    this.progressRef = 0;
    // 博客类型 0 仅文字 1 图文 2视频文字
    this.blogType = "0";
    // 图文博客中的图
    this.blogImageArr = [];
    // 视频信息
    this.videoUploadRef = {};
  }
}
</script>

<style lang="less" scoped>
@import url("../../assets/less/global.less");
@import url("./index.less");
</style>